<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <title>Document</title>
  </head>
  <body>
    <h4 class="city"></h4>
    <div class="search">
      <input id="kw" type="text" placeholder="城市名称" />
      <button id="searchBtn">查询</button>
    </div>
    <div class="weather"></div>
    <script>
      // 封装请求
      function request(
        url,
        method = "GET",
        params = {},
        data = {},
        config = {}
      ) {
        return new Promise((resolve, reject) => {
          /*
          axios({
            url,
            method,
            params,
            data,
          })
            .then((data) => {
              resolve(data)
            })
            .catch((err) => {
              reject("请求失败")
            })
          */

          if (method.toLowerCase() == "get") {
            axios.get(url, config).then(({ data }) => {
              resolve(data)
            })
          } else if (method.toLowerCase() == "post") {
            axios.post(url, data, config).then((data) => {
              resolve(data)
            })
          }
        })
      }

      // 1. 自动IP定位
      request(
        "https://restapi.amap.com/v3/ip?key=e45ba07980d4a0817d2edeba0de23add"
      ).then((data) => {
        $(".city").text(data.city)
        // 查询天气
        getWeather(data.city)
      })

      // 2. 根据输入城市名称，查询天气
      $("#searchBtn").click(() => {
        const val = $("#kw").val()
        if (val) {
          $(".city").text(val)
          getWeather(val)
        }
      })

      // 封装天气查询方法
      function getWeather(cityname) {
        const url = `https://restapi.amap.com/v3/weather/weatherInfo?key=e45ba07980d4a0817d2edeba0de23add&city=${cityname}&extensions=all`
        request(url).then(({ forecasts }) => {
          $(".weather").html("") // 先清空旧数据
          const casts = forecasts[0].casts
          // console.log(casts)
          casts.forEach((item) => {
            const div = document.createElement("div")
            div.innerHTML = `<p>日期:${item.date}</p><p>气温:${item.nighttemp}℃~${item.daytemp}℃</p><p>风力:${item.nightpower}${item.nightwind}风~${item.daypower}${item.daywind}风</p>`
            $(".weather").append(div)
          })
        })
      }
    </script>
  </body>
</html>
